/*************************************************************************
	> File Name: net_opt.c
	> function: 语音听写(iFly Auto Transform)技术能够实时地将语音转换成对应的文字。
	> Author:卢孙远(Simon)
	> company: GDOU
	> Mail: lsy476941913@live.com 
	> Created Time: 2017年03月28日 星期二 12时33分36秒
 ************************************************************************/
#include "net_opt.h"
int sockfd_asr = -1;
/*初始化socket，等待客户端连接*/

void init_sock(void)
{
	// recv socket
	struct sockaddr_in sin;
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);

	int on = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(1));//设置socket选项，套接字重复利用

	bzero((char *) &sin, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = htonl(INADDR_ANY);	
	sin.sin_port = htons(atoi(DEF_PORT));

	int ret = bind(sockfd, (struct sockaddr *)&sin, sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind() failed");
		exit(0);
	}

	listen(sockfd, 3);//最多可以三台终端可以连接

	printf("wait for connecting ... \n");
	socklen_t addrlen = sizeof(struct sockaddr);
	
	while(1)
	{		
		sockfd_asr = accept(sockfd, (struct sockaddr *)&sin, &addrlen);
		if(sockfd_asr < 0)
		{
			if(errno == EINTR)
				continue;
			perror("accpet()");
			exit(1);
		}
		else
			break;
	}
	
	printf("new connection: %s: %hu \n", inet_ntoa(sin.sin_addr),
									ntohs(sin.sin_port));
}


const char *get_audio_file(void)
{
	char *pcm = calloc(1, 96000);
	
	printf("waiting for data...\n");

	gec210_ip = calloc(1, 32);

	int n, total_bytes = 96000, m=0;
	char *tmp = pcm;
	while(total_bytes > 0)
	{
		n = read(sockfd_asr, tmp, total_bytes);

		if(n == -1)
		{
			perror("read() failed");
			exit(0);
		}
		if(n == 0)
		{
			printf("[%d]recv finished. get %d bytes\n", __LINE__, m);
			break;
		}

		total_bytes -= n;
		tmp += n;
		m += n;
	}

	printf("[%d]recv finished. get %d bytes\n", __LINE__, m);

	int pcmfd = open("pcm/cmd.pcm", O_WRONLY|O_CREAT|O_TRUNC, 0644);
	m = write(pcmfd, pcm, 96000);
	printf("%d bytes has been wirtten into pcm/cmd.pcm\n", m);
	close(pcmfd);

	return "pcm/cmd.pcm";

}

//讲pc语音引擎端返回的xml数据显示到屏幕和发送到arm客户终端
void show_result(char *string, char is_over)
{
	printf("\rResult:\n%s", string);
	if(is_over)
		putchar('\n');

	static int first_time = 1;
	if(first_time == 1)
	{
		if(!access("result.xml", F_OK))	
			system("rm result.xml");
		first_time = 0;
	}

	FILE *result;
	result = fopen("result.xml", "a");
	//将xml结果附加到result.xml
	fwrite(string, strlen(string), 1, result);
	fclose(result);
	
	//将xml结果反馈到arm客户终端
	int count = write(sockfd_asr, string, strlen(string));
	if(count == -1)
	{
		perror("write socket failed");
		exit(0);
	}
	printf("%d bytes has been sent to socket.\n", count);
}